package com.heima.behavior.service.impl;

import com.heima.behavior.dto.BehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessageDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApCollectionBehavior;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApBehaviorService;
import com.heima.behavior.service.IApCollectionBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP收藏信息表 服务实现类
 * </p>
 *
 * @author Wq
 * @since 2022-10-18
 */
@Service
public class ApCollectionBehaviorServiceImpl implements IApCollectionBehaviorService {

    @Autowired
    private IApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IApBehaviorService apBehaviorService;

    @Override
    public ResponseResult saveApCollection(BehaviorDto dto) {

        //保存到行为实体表  生成EntryId
        ApBehaviorEntry entry = apBehaviorEntryService.getEntryByUserId(dto.getUserId());
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //组装数据
        ApCollectionBehavior apCollectionBehavior = new ApCollectionBehavior();
        apCollectionBehavior.setEntryId(entry.getEntryId());
        apCollectionBehavior.setOperation(dto.getOperation());
        apCollectionBehavior.setArticleId(dto.getArticleId());
        apCollectionBehavior.setCollectionTime(new Date());
        //保存到MongoDBHong 中
        mongoTemplate.save(apCollectionBehavior);
        //保存kafka
        UpdateArticleMessageDto articleMessage = new UpdateArticleMessageDto();
        articleMessage.setType(2);
        articleMessage.setArticleId(dto.getArticleId());
        articleMessage.setAdd(dto.getOperation() == 0 ? 1 : -1);
        //使用多线程异步往kafka发送
        apBehaviorService.sendBehaviorMessageToKafka(articleMessage);

        return ResponseResult.okResult();
    }


}
